package com.coincalf.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Autowired
    private TokenInterceptor tokenInterceptor;

    //无需token拦截
    public static final String[] notTokenInterceptors = {
            "/coin/info/*",
            "/user/service/register",
            "/trade/market/getBySymbol/*",
            "/account/recharge",
            "/coin/serverUrl/*",
            "/coin/contract/*",
            "/coin/mainCoinId/*",
            "/dc/*",
            "/hz/notice/hug/index",
            "/websocket/**",
            "/ws/**",

            "/trade/market/queryTradeMarkets",
            "/forex_area/list",
            "/forex/market/queryForexMarkets",
            "/trade/market/queryTradeMarketsByIds",
            "/forex/market/queryForexMarketsByIds",
            "/trade/market/refresh/*",
            "/forex/market/refresh/*",
            "/trade/market/depth/**",
            "/trading_area/list",
            "/forex/market/all",
            "/trade/market/all",
            "/trade/market/all2",
            "/trade/market/trades/**",
            "/trade/order/turnover/*",
            "/account/recharge",
            "/match/trade",
            "/swagger-resources/**",
            "/webjars/**",
            "/swagger-ui.html/**"
    };

    /**
     * 拦截器注册 可注册多个 执行顺序和注册顺序一样
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //拦截器的执行顺序取决与注册顺序
        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(MvcConfig.notTokenInterceptors);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedMethods("*")
                        .allowedHeaders("*")
                        .allowCredentials(true)
                        .exposedHeaders(HttpHeaders.SET_COOKIE)
                        .maxAge(3600L);
            }
        };
    }


    /**
     * 开启websocket支持
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}
